<?php
class SiteManager_SpecialOffersController extends SiteManagerController
{

   	public function indexAction() {
   		$iPage = intval($this->getRequest()->getParam('page', 1));
    	$this->view->offers = Obj_SpecialOffer::getPaginatedSpecialOffers($iPage);
    }

   	public function editAction() {
   	$id = (int) $this->getRequest()->getParam('id', 0);
		$addnew = intval($this->getRequest()->getParam('addnew', 0)) === 1 ? true : false;
		$arOffer = Obj_SpecialOffer::getSpecialOffer($id);
		if ($addnew || $arOffer === false) {
    		$this->view->spec_offer = array(
	    		'ID' 			=> 0,
	    		'Title' 		=> '',
	    		'startDate'		=> '',
	    		'endDate'		=> '',
	    		'Content' 		=> '',
	    		'active' 		=> 0,
	    		'author' 		=> '',
	    		'seoTitle' 		=> '',
	    		'seoKeywords' 	=> '',
	    		'seoDescription'=> '',
	    		'date' 			=> ''
    		);
    	}
    	else {
    		$this->view->spec_offer = $arOffer;
    	}
    }

    public function saveAction() {
		if (!$this->_isAJAX) {
				throw new Zend_Exception(_('Эта функция Вам недоступна'));
		}
		$id = (int) $this->getRequest()->getParam('ID', 0);
		$arOffer = array();
		$arOffer['Title'] = trim($this->getRequest()->getParam('Title', ''));
		$arOffer['Content'] = trim($this->getRequest()->getParam('Content', ''));
		$arOffer['active'] = (int)intval($this->getRequest()->getParam('active', 0));
		$arOffer['seoTitle'] = trim($this->getRequest()->getParam('seoTitle', ''));
		$arOffer['seoKeywords'] = trim($this->getRequest()->getParam('seoKeywords', ''));
		$arOffer['seoDescription'] = trim($this->getRequest()->getParam('seoDescription', ''));
		$arOffer['date'] = date("Y-m-d H:i:s", time());
		
		$arOffer['startDate'] =  trim($this->getRequest()->getParam('startDate', ''));
		$arOffer['endDate'] =  trim($this->getRequest()->getParam('endDate', ''));

		$arOffer['author'] = 0;
    	if (Zend_Auth::getInstance()->hasIdentity()) {
	    	$user = Zend_Auth::getInstance()->getIdentity();
    		$arOffer['author'] = (int)$user->ID;
    	}
		$allOffers = Obj_SpecialOffer::getAllSpecialOffers();
		$errors = array('is_error' => 0, 'err_string' => '');
        if($id != 0){
			$current_offer = Obj_SpecialOffer::getSpecialOffer($id);
			if(	
				$arOffer['Title'] == $current_offer['Title'] &&
				$arOffer['startDate'] == $current_offer['startDate'] &&
				$arOffer['endDate'] == $current_offer['endDate'] &&
				$arOffer['Content'] == $current_offer['Content'] && 
				$arOffer['active'] == $current_offer['active'] && 
				$arOffer['seoTitle'] == $current_offer['seoTitle'] && 
				$arOffer['seoDescription'] == $current_offer['seoDescription'] && 
				$arOffer['seoKeywords'] == $current_offer['seoKeywords']
			){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Даная новость уже существует. Нет необходимости в повторном добавлении!\n";
			}
			if((int)strtotime($arOffer['startDate']) > (int)strtotime($arOffer['endDate'])){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Дата окончания акции не может быть ранее чем дата ее начала!\n";			
			}
			if($arOffer['Title'] == ''){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Задайте заголовок страницы!\n";
			}
			if(strlen($arOffer['Title']) > 255){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Заголовок страницы слишком длинный!\n";
			}
			if(strip_tags($arOffer['Content']) == ""){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Контент страницы не может быть пустым!\n";
			}
		} else {
			if((int)strtotime($arOffer['startDate']) > (int)strtotime($arOffer['endDate'])){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Дата окончания акции не может быть ранее чем дата ее начала!\n";			
			}
			if($arOffer['Title'] == ''){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Задайте заголовок страницы!\n";
			}
			if($arOffer['startDate'] == ''){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Задайте дату начала акции!\n";
			}
			if($arOffer['endDate'] == ''){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Задайте дату окончания акции!\n";
			}
			if(strlen($arOffer['Title']) > 254){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Заголовок страницы слишком длинный!\n";
			}
			if(trim(strip_tags($arOffer['Content'])) == ""){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Контент страницы не может быть пустым!\n";
			}
		}
		foreach ($allOffers as $v){
			if ($v['Title'] == $arOffer['Title'] && $id != 0 && $id != $v['ID']){
				$errors['is_error'] = 1;
				$errors['err_string'] .= "Специальное предложение з таким заголовком уже существует!\n";					
			}
			
		}
		if($errors['is_error'] == 1){
			$this->view->error = $errors['err_string'];
			$this->_helper->json(array('error' => 1, 'errorStr' => $errors['err_string']), true, false);
			return;
			die();
		}

		$offer_id = Obj_SpecialOffer::saveSpecialOffer($arOffer, $id);
		
		if ($arOffer['active'] === 1){
    		Obj_System_SearchIndex::write($offer_id, CONTENT_TYPE_SPECIAL_OFFER, $arOffer['Title'], strip_tags($arOffer['Content']));
    	} else {
    		Obj_System_SearchIndex::delete($offer_id, CONTENT_TYPE_SPECIAL_OFFER);
    	} 
		$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('module' => 'site-manager', 'controller'=>'special-offers',  'action' => 'index'))), true, false);
    }

    public function deleteAction() {
		if (!$this->_isAJAX) {
			throw new Zend_Exception(_('Эта функция Вам недоступна'));
		}
		$id = (int) $this->getRequest()->getParam('id', 0);
		Obj_SpecialOffer::delSpecialOffer($id);
		
		Obj_System_SearchIndex::delete($id, CONTENT_TYPE_SPECIAL_OFFER);
    	$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('module' => 'site-manager', 'controller'=>'special-offers',  'action' => 'index'))), true, false);
    }

    public function groupedDeleteAction(){
    	if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$arDelete = array();
    	$arDelete = $this->getRequest()->getParam('arDelete', null);
    	foreach ($arDelete as $k => $v){
	    	$id = (int) $v;
	    	Obj_SpecialOffer::delSpecialOffer($id);
	    	Obj_System_SearchIndex::delete($id, CONTENT_TYPE_SPECIAL_OFFER);
    	}
		$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('module' => 'site-manager', 'controller'=>'special-offers',  'action' => 'index'))), true, false);
    }

    public function stateChangerAction() {
		if (!$this->_isAJAX) {
    		throw new Zend_Exception(_('Эта функция Вам недоступна'));
    	}
    	$id = (int) $this->getRequest()->getParam('id', 0);
    	$arOffer = Obj_SpecialOffer::getSpecialOffer($id);
    	if(intval($arOffer['active']) === 1){
    		$arOffer['active'] = 0;
    		$nid = Obj_SpecialOffer::saveSpecialOffer($arOffer, $id);
    		Obj_System_SearchIndex::delete($nid, CONTENT_TYPE_SPECIAL_OFFER);
    	} else {
    		$arOffer['active'] = 1;
    		$nid = Obj_SpecialOffer::saveSpecialOffer($arOffer, $id);
    		Obj_System_SearchIndex::write($nid, CONTENT_TYPE_SPECIAL_OFFER, $arOffer['Title'], $arOffer['Content']);
    	}
    	$this->_helper->json(array('error' => 0, 'redirect' => $this->view->url(array('module' => 'site-manager', 'controller'=>'special-offers',  'action' => 'index'))), true, false);
    }
}